package com.ruoyi.business.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.business.domain.TResourceInfo;
import com.ruoyi.business.domain.TResourceProgress;
import com.ruoyi.business.mapper.TResourceInfoMapper;
import com.ruoyi.business.service.ITResourceInfoService;
import com.ruoyi.business.service.ITResourceProgressService;
import com.ruoyi.business.vo.TResourceInfoVo;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * 资源中心Service业务层处理
 *
 * @author Tellsea
 * @date 2024-01-17
 */
@Service
@RequiredArgsConstructor
public class TResourceInfoServiceImpl extends ServiceImpl<TResourceInfoMapper, TResourceInfo> implements ITResourceInfoService {

    private final ITResourceProgressService resourceProgressService;

    @Override
    public TableDataInfo<TResourceInfoVo> queryList(TResourceInfoVo entity) {
        Page<TResourceInfoVo> page = this.baseMapper.queryList(PageUtils.buildPage(), entity);
        List<TResourceProgress> resourceProgressList = resourceProgressService.list(Wrappers.<TResourceProgress>lambdaQuery()
                .eq(TResourceProgress::getUserId, SecurityUtils.getLoginUser().getUser().getUserId()));
        page.getRecords().forEach(item -> resourceProgressList.forEach(progress -> {
            if (progress.getResourceId().equals(item.getId())) {
                item.setProgress(progress.getProgress());
            }
        }));
        return PageUtils.buildDataInfo(page);
    }

    @Override
    public List<TResourceInfoVo> queryAll(TResourceInfoVo entity) {
        return this.baseMapper.queryList(entity);
    }

    @Override
    public TResourceInfoVo queryById(Long id) {
        TResourceInfoVo vo = this.baseMapper.queryById(id);
        List<TResourceProgress> resourceProgressList = resourceProgressService.list(Wrappers.<TResourceProgress>lambdaQuery()
                .eq(TResourceProgress::getUserId, SecurityUtils.getLoginUser().getUser().getUserId())
                .eq(TResourceProgress::getResourceId, id));
        if (CollUtil.isNotEmpty(resourceProgressList)) {
            if (resourceProgressList.size() > 1) {
                throw new ServiceException("进度异常，存在多个");
            } else {
                vo.setProgress(resourceProgressList.get(0).getProgress());
            }
        } else {
            vo.setProgress(BigDecimal.ZERO);
        }
        return vo;
    }
}
